package com.atxiaodei.springbootkabudazkapi.zookeepercrud;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName CreateZookeeperDemo
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2022/1/16 21:52
 * @Version 1.0
 **/
public class CreateZookeeperDemo {

    public void create() throws Exception {
        CuratorFramework client= CuratorFrameworkFactory
                .builder()
                .connectionTimeoutMs(50000)
                .connectString("192.168.0.108:2181") //读写分离(zookeeper-server)
                // baseSleepTimeMs*Math.max(1,random.nextInt(1<<(maxRetries+1))
                /**
                 * RetryNTimes 指定最大重试次数
                 * RetryOneTimes
                 * RetryUntilElapsed 一直重试，直到达到规定时间
                 */
                .retryPolicy(new ExponentialBackoffRetry(1000,3))
                .sessionTimeoutMs(15000)
                // 名称空间 每次操作zk /kabuda
                .namespace("kabuda")
                .build();
        client.start(); //启动
        // 基本创建
        String path = client.create().forPath("/app1");
        // 创建节点带有数据
        client.create().forPath("/app2", "Hello Zookeeper".getBytes());
        // 设置节点类型
        client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/app3");
        // 创建多级节点
        client.create().creatingParentsIfNeeded().forPath("/app4/p2","kabuda爱学习".getBytes());
        System.out.println(path);
        TimeUnit.SECONDS.sleep(10);
    }

    public static void main(String[] args) throws Exception {
        CreateZookeeperDemo createZookeeperDemo=new CreateZookeeperDemo();
        createZookeeperDemo.create();
    }
}
